package com.smart.campus.web.controller.school;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.campus.common.utils.DateUtils;
import com.smart.campus.school.domain.ClassInfo;
import com.smart.campus.school.domain.Grade;
import com.smart.campus.school.domain.query.IllegalRecordQuery;
import com.smart.campus.school.domain.vo.IllegalRecordReportVo;
import com.smart.campus.school.domain.vo.IllegalRecordVo;
import com.smart.campus.school.service.IClassInfoService;
import com.smart.campus.school.service.IGradeService;
import com.smart.campus.web.utils.SchoolUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.IllegalRecord;
import com.smart.campus.school.service.IIllegalRecordService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

import static com.smart.campus.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * 违规记录Controller
 * 
 * @author Zhihe.Li
 * @date 2020-05-25
 */
@Controller
@RequestMapping("/school/illegalRecord")
public class IllegalRecordController extends BaseController
{
    private String prefix = "school/illegalRecord";

    @Autowired
    private IIllegalRecordService illegalRecordService;

    @Autowired
    private IClassInfoService classInfoService;

    @Autowired
    private IGradeService gradeService;

    @RequiresPermissions("school:illegalRecord:view")
    @GetMapping()
    public String illegalRecord()
    {
        return prefix + "/illegalRecord";
    }

    /**
     * 查询违规记录列表
     */
    @RequiresPermissions("school:illegalRecord:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(IllegalRecordQuery query)
    {
        startPage();
        List<IllegalRecordVo> list = illegalRecordService.selectIllegalRecordList(query);
        return getDataTable(list);
    }

    /**
     * 导出违规记录列表
     */
    @RequiresPermissions("school:illegalRecord:export")
    @Log(title = "违规记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(IllegalRecordQuery illegalRecord)
    {
        List<IllegalRecordVo> list = illegalRecordService.selectIllegalRecordList(illegalRecord);
        ExcelUtil<IllegalRecordVo> util = new ExcelUtil<IllegalRecordVo>(IllegalRecordVo.class);
        return util.exportExcel(list, "illegalRecord");
    }

    /**
     * 新增违规记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存违规记录
     */
    @RequiresPermissions("school:illegalRecord:add")
    @Log(title = "违规记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(IllegalRecord illegalRecord) {
        illegalRecord.setSchoolId(SchoolUtil.getSchoolId());
        illegalRecord.setStatus(1);
        return toAjax(illegalRecordService.insertIllegalRecord(illegalRecord));
    }

    /**
     * 修改违规记录
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        IllegalRecordVo illegalRecord = illegalRecordService.selectIllegalRecordById(id);
        mmap.put("illegalRecord", illegalRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存违规记录
     */
    @RequiresPermissions("school:illegalRecord:edit")
    @Log(title = "违规记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(IllegalRecord illegalRecord)
    {
        return toAjax(illegalRecordService.updateIllegalRecord(illegalRecord));
    }

    /**
     * 删除违规记录
     */
    @RequiresPermissions("school:illegalRecord:remove")
    @Log(title = "违规记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(illegalRecordService.deleteIllegalRecordByIds(ids));
    }



    /**
     * 查询违规记录报表
     */
    @PostMapping("/getReport")
    @ResponseBody
    public List<Map<String,Object>> getReport(IllegalRecordQuery query)
    {

        List<Map<String,Object>> mapList = new ArrayList<>();
        Grade gradeParam = new Grade();
        gradeParam.setShcoolId(SchoolUtil.getSchoolId());
        List<Grade> gradeList = gradeService.selectGradeList(gradeParam);

        for (Grade grade : gradeList) {
            Map<String,Object> map = new HashMap<>();
            ClassInfo classInfo = new ClassInfo();
            classInfo.setGradeId(grade.getId());
            List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(classInfo);
            dateParamsHandler(query);
            List<String> classNameList = new ArrayList<>();
           // classNameList.add("");
            JSONArray jsonArray = new JSONArray();
            JSONObject awardJsonObject = new JSONObject();
            awardJsonObject.put("name","奖励分数");
            awardJsonObject.put("type","line");
            awardJsonObject.put("stack","总量");
            JSONObject illJsonObject = new JSONObject();
            illJsonObject = new JSONObject();
            illJsonObject.put("name","惩罚分数");
            illJsonObject.put("type","line");
            illJsonObject.put("stack","总量");
            List<Float> awardDataList = new ArrayList<>();
            List<Float> illDataList = new ArrayList<>();
            for (ClassInfo info : classInfoList) {
                query.setClassId(info.getId());
                List<IllegalRecordReportVo> list = illegalRecordService.selectIllegalRecordReport(query);
                List<Float> awardList = list.stream().filter(e->e.getType()==1).map(e -> e.getScore()).collect(Collectors.toList());
                logger.info("班级[{}],awardList:{}",info.getId(),awardList);
                if(CollectionUtils.isEmpty(awardList)){
                    awardList.add(0f);
                }
                awardDataList.addAll(awardList);

                List<Float> illList = list.stream().filter(e->e.getType()==2).map(e -> e.getScore()).collect(Collectors.toList());
                if(CollectionUtils.isEmpty(illList)){
                    illList.add(0f);
                }
                classNameList.add(info.getClassName());

                illDataList.addAll(illList);
            }

            awardJsonObject.put("data",awardDataList.toArray());
            illJsonObject.put("data",illDataList.toArray());
            jsonArray.add(awardJsonObject);
            jsonArray.add(illJsonObject);
            map.put("series",jsonArray);
            map.put("classNameList",classNameList);
            map.put("grade",grade);
            mapList.add(map);
            logger.info("report result :"+ JSON.toJSONString(map));
        }
        logger.info("报表结果："+JSON.toJSONString(mapList));
        return mapList;
    }

    /**
     * 查询时间类型处理
     * @param query
     */
    private void dateParamsHandler(IllegalRecordQuery query){
        Map<String, Object> params = query.getParams();

        Date bgDate = null,edDate = null;
        switch (query.getQueryType()){
            case 1:
                bgDate = DateUtils.getCurrentMonthStartTime();
                edDate = DateUtils.getCurrentMonthEndTime();
                break;
            case 2:
                bgDate = DateUtils.addMonths(new Date(),-6);
                edDate = new Date();
                break;
            default:
                bgDate = DateUtils.getCurrentWeekDayStartTime();
                edDate = DateUtils.getCurrentWeekDayEndTime();
                break;
        }
        params.put("beginTime",DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS,bgDate));
        params.put("endTime",DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS,edDate));
        query.setParams(params);
    }
    @RequiresPermissions("school:illegalRecord:report")
    @GetMapping("/report")
    public String report()
    {
        return prefix + "/report";
    }
}
